package com.dragon.utilslibrary.tools;

import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Vibrator;
import android.text.TextUtils;

import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 公用的Util类
 */
public class CommonUtils {

    private static long lastClickTime;

    /**
     * 验证有效MAC地址
     *
     * @param mac
     * @return
     */
    public static boolean isvalidateMac(String mac) {
        if (mac == null) {
            return false;
        }
        Pattern p0 = Pattern.compile("^([a-fA-F0-9]{2}[:-]){5}[a-fA-F0-9]{2}$");
        Matcher m0 = p0.matcher(mac);
        Pattern p1 = Pattern.compile("^([a-fA-F0-9]{4}\\.){2}[a-fA-F0-9]{2}$");
        Matcher m1 = p1.matcher(mac);
        return (m0.find() || m1.find()) ? true : false;
    }

    public static boolean isNumberCombine(String userid) {
        /**
         * (?!^\d+$)  排除全数字
         (?!^[a-zA-Z]+$) 排除全字母
         [0-9a-zA-Z]{4,23} 字符或字母4-23位，不考虑全为数字和全为字符情况。
         */
        Pattern p0 = Pattern.compile("^(?!^\\d+$)(?!^[a-zA-Z]+$)[0-9a-zA-Z]{20,40}$");
        Matcher m0 = p0.matcher(userid);
        return m0.find();
    }

    public static boolean isPasswordCombine(String userid) {
        Pattern p0 = Pattern.compile("^[0-9a-zA-Z_]{8,20}$");
        Matcher m0 = p0.matcher(userid);
        return m0.find();
    }

    /**
     * 验证邮箱
     *
     * @param email
     * @return
     */
    public static boolean isEmailFormat(String email) {
        boolean tag = true;
        final String pattern1 = "^([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|_|.]?)*[a-zA-Z0-9]+.[a-zA-Z]{2,4}$";
        final Pattern pattern = Pattern.compile(pattern1);
        final Matcher mat = pattern.matcher(email);
        if (!mat.find()) {
            tag = false;
        }
        return tag;
    }

    /**
     * 判断email格式是否正确
     *
     * @param email
     * @return
     */
    public static boolean isEmail(String email) {
        String str = "^([A-Z0-9a-z._%+-])+@([A-Za-z0-9.-])+\\.[A-Za-z]{2,4}$";
//        String str = "^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
        Pattern p = Pattern.compile(str);
        Matcher m = p.matcher(email);
        return m.matches();
    }


    /**
     * 创建缓存文件的名字 用"_"代替 "/"
     *
     * @param url
     * @return
     */
    public static String buildImgName(String url) {
        return (url == null ? null : url.replace("/", "_"));
    }

    /**
     * 用"'"代替"."
     * @param numbler
     * @return
     */
    public static String instandPoint(String numbler) {
        return (numbler == null ? null : numbler.replace(".", "'"));
    }

    /**
     * 启动震动服务
     *
     * @param context
     * @param time
     */
    public static void vibrator(Context context, int time) {
        if (context != null) {
            Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
            vibrator.vibrate(time);
        }
    }

    /**
     * vibratePattern = new long[] {200, 1500};
     *
     * @param context
     */
    public static void vibrator(Context context) {
        long[] vibratePattern = new long[]{200, 1500};
        if (context != null) {
            Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
            vibrator.vibrate(vibratePattern, 0);
        }
    }

    public static boolean isHanzi(String input) {
        if (input == null || "".equals(input))
            return false;
        Pattern pa = Pattern.compile("^[\u4e00-\u9fa5]*$ ");
        Matcher matcher = pa.matcher(input);
        return matcher.find();
    }

    /**
     * 判断当前系统语言环境是否为中文
     *
     * @param context
     * @return
     */
    public static boolean isChinaFont(Context context) {
        if (context == null) return true;
        Locale locale = context.getResources().getConfiguration().locale;
        String country = locale.getCountry();
        if ("CN".equals(country)) {
            return true;
        }
        return false;
    }

    /**
     * 根据手机分辨率从dp转成px
     *
     * @param context
     * @param dpValue
     * @return
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f) - 15;
    }

    /**
     * 防止快速多次点击
     */
    public static boolean isFastDoubleClick() {
        long time = System.currentTimeMillis();
        long timeD = time - lastClickTime;
        if (0 < timeD && timeD < 500) {
            return true;
        }
        lastClickTime = time;
        return false;
    }

    /**
     * 获取APP版本号
     *
     * @param context
     * @return
     */
    public static String getAPPVersion(Context context) {
        PackageManager manager;
        PackageInfo info = null;
        manager = context.getPackageManager();
        try {
            info = manager.getPackageInfo(context.getPackageName(), 0);
            return "V" + info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();

        }
        return null;
    }

    /**
     * 把unicode编码的字符串转成中文，dataStr兼容（中英文，标点等混合）
     *
     * @param dataStr
     * @return
     */
    public static String decodeUnicode(String dataStr) {
        final StringBuffer buffer = new StringBuffer();
        if (!TextUtils.isEmpty(dataStr)) {
            String[] arr = dataStr.split("\\\\u");
            for (int i = 0; i < arr.length; i++) {
                try {
                    if (i == 0 && arr[0] != null) {
                        buffer.append(arr[0]);
                    }
                    if (i > 0) {
                        if (arr[i] != null) {
                            if (arr[i].length() > 4) {
                                String str = arr[i].substring(0, 4);
                                buffer.append((char) Integer.parseInt(str, 16));
                                buffer.append(arr[i].substring(4, arr[i].length()));
                            } else if (arr[i].length() <= 4) {
                                buffer.append((char) Integer.parseInt(arr[i], 16));
                            }
                        }
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        return buffer.toString();
    }

    public static boolean isEmtype(String dataStr) {
        if (dataStr == null || "".equals(dataStr) || "null".equals(dataStr)) {
            return true;
        }
        return false;
    }

    /**
     * 步数转为卡路里 单位卡
     * @param sportStep 运动步数
     * @param weight 体重
     * @param isTotalCal 是否为总卡路里
     * @return
     */
    public static int step2Cal(String sportStep, int weight, boolean isTotalCal)   //  cm/ 2s
    {
        int step = 0;
        if(sportStep == null || sportStep.equals("")){
            return   0;
        } else {
            step = Integer.parseInt(sportStep);
        }

        if (weight < 25 || weight > 300) {
            weight = 70;
        }
        int K = 420;
        if (!isTotalCal){
            K = 418;//418064;
            if(step <= 4)
                K = 540;//540135;
            else if(step <= 5)
                K = 601;//601170;
            else if(step < 10)
                K = 662;//662205;
            else;
        }

        int calories;
        calories= (K* weight * step)/1000;
        return calories;
    }

    /**
     * 步数转为距离 单位厘米cm
     * @param sportStep 运动步数
     * @param height 身高
     * @param sex 性别
     * @return
     */
    public static int step2Distance(String sportStep, int height, int sex){
        int step = 0;
        int rate_to_height;
        if(sportStep == null || sportStep.equals("")){
            return   0;
        } else {
            step = Integer.parseInt(sportStep);
        }
        if (height == 0 || height > 400) {
            height = 170;
        }
        if (sex == 0){
            rate_to_height  = 413;
        } else {
            rate_to_height  = 415;
        }
        rate_to_height += 40;
        int distance = (step * rate_to_height * height)/1000;
        return distance;
    }

    /**
     * cm转m和km
     * @param cm
     * @return
     */
    public static int cmToMOrKm(int cm){
        int distance;
        DecimalFormat decimalFormat = new DecimalFormat("0", new DecimalFormatSymbols(Locale.US));
        String format;
        if (cm < 100){
            format = decimalFormat.format(1);
        } else {
            format = decimalFormat.format(cm*1.0/100.0);
        }
        distance = (int) Float.parseFloat(format);
        return distance;
    }


}
